<template>
  <div class="change-password-container">
    <!-- 顶部导航栏 -->
    <el-header class="navbar">
      <div class="logo">思而罔学习平台</div>
      <el-menu mode="horizontal" :default-active="activeMenu" @select="handleSelect">
        <el-menu-item index="1" @click="goBackHome">首页</el-menu-item>
        <el-menu-item index="2" @click="goToPersonal">个人中心</el-menu-item>
        <el-menu-item index="3" @click="goToCollection">我的收藏</el-menu-item>
      </el-menu>
      <div class="auth-buttons">
        <span class="welcome-text">欢迎, {{ userInfo.username }}</span>
        <el-button type="text" @click="logout">退出登录</el-button>
      </div>
    </el-header>

    <!-- 密码修改表单 -->
    <el-main class="main-content">
      <el-card class="password-form-card">
        <div class="form-header">
          <h2>修改密码</h2>
          <p>为了保障账户安全，请设置一个强密码</p>
        </div>

        <el-form
            :model="passwordForm"
            :rules="rules"
            ref="passwordFormRef"
            label-width="100px"
            label-position="top"
        >
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入当前使用的密码"
                show-password
            ></el-input>
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
                @input="checkPasswordStrength"
            ></el-input>
            <div class="password-strength" v-if="passwordForm.newPassword">
              <div class="strength-bar" :class="strengthClass"></div>
            </div>
            <div class="password-strength-text" v-if="passwordForm.newPassword">
              密码强度: {{ strengthText }}
            </div>
          </el-form-item>

          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
            ></el-input>
          </el-form-item>

          <div class="password-tips">
            <p>密码要求：</p>
            <ul>
              <li :class="{'valid': hasLength}">至少8个字符</li>
            </ul>
          </div>

          <el-form-item>
            <el-button
                type="primary"
                @click="submitForm"
                :loading="submitting"
            >
              确认修改
            </el-button>
            <el-button @click="goToPersonal">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-main>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from "@/api/server"
import { useUserStore } from '@/store/useUserstore'

const router = useRouter()
const userStore = useUserStore()
const passwordFormRef = ref(null)

// 顶部导航栏激活状态
const activeMenu = ref('2')

// 用户信息
const userInfo = reactive({
  username: userStore.userInfo.username || '用户'
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码强度相关
const passwordStrength = ref(0) // 0-4
const strengthText = computed(() => {
  const texts = ['非常弱', '弱', '中等', '强', '非常强']
  return texts[passwordStrength.value]
})
const strengthClass = computed(() => {
  return `strength-${passwordStrength.value}`
})

// 密码要求状态
const hasLength = computed(() => passwordForm.newPassword.length >= 8)
const hasUppercase = computed(() => /[A-Z]/.test(passwordForm.newPassword))
const hasLowercase = computed(() => /[a-z]/.test(passwordForm.newPassword))
const hasNumber = computed(() => /[0-9]/.test(passwordForm.newPassword))
const hasSpecialChar = computed(() => /[!@#$%^&*]/.test(passwordForm.newPassword))

// 检查密码强度
const checkPasswordStrength = () => {
  let strength = 0

  if (hasLength.value) strength += 1
  if (hasUppercase.value) strength += 1
  if (hasLowercase.value) strength += 1
  if (hasNumber.value) strength += 1
  if (hasSpecialChar.value) strength += 1

  // 将强度映射到0-4的范围内
  passwordStrength.value = Math.min(4, strength)
}

// 表单验证规则
const rules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少为8个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === passwordForm.oldPassword) {
          callback(new Error('新密码不能与旧密码相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 提交状态
const submitting = ref(false)

// 菜单选择处理
const handleSelect = (index) => {
  console.log('当前菜单项：', index)
}

// 导航方法
const goBackHome = () => router.push('/home')
const goToPersonal = () => router.push('/personal')
const goToCollection = () => router.push('/collection')
const logout = async () => {
  try {
    await axios.post('/users/logout'); // 会自动带上 Bearer token
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    ElMessage.success('退出成功');
    await router.push('/');
  } catch (error) {
    console.error('退出失败：', error);
    ElMessage.error('退出失败');
  }
};
// 提交表单
const submitForm = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (!valid) {
      return false
    }

    // 检查密码强度
    if (passwordStrength.value < 1) {
      ElMessage.warning('密码强度不足，请设置更复杂的密码')
      return
    }

    submitting.value = true

    try {
      const data = {
        userId: userStore.userInfo.userId,
        oldPassword: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword,
        reNewPassword: passwordForm.confirmPassword
      }

      const response = await axios.put('/users/editPassword', data)

      if (response.data.code === 1) {
        ElMessage.success('密码修改成功，请重新登录。')
        // 清空表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
        await router.push('/');
      } else {
        ElMessage.error(response.data.msg || '密码修改失败')
      }
    } catch (error) {
      console.error('修改密码失败', error)
      ElMessage.error('修改密码失败，请稍后重试')
    } finally {
      submitting.value = false
    }
  })
}
</script>

<style scoped>
@import "../styles/Home.css";
/* 密码修改页面主体样式 */
.change-password-container {
  background-color: var(--bg);
  min-height: 100vh;
}

.main-content {
  padding: 40px;
  max-width: 800px;
  margin: 0 auto;
}

.password-form-card {
  padding: 30px;
  border-radius: 12px !important;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08) !important;
  border: none !important;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.password-form-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12) !important;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 24px;
  color: var(--text);
  font-weight: 600;
  margin-bottom: 10px;
}

.form-header p {
  color: var(--text-light);
  font-size: 14px;
}

/* 密码强度指示器 */
.password-strength {
  margin-top: 8px;
  height: 4px;
  background-color: #e0e0e0;
  border-radius: 2px;
  overflow: hidden;
}

.strength-bar {
  height: 100%;
  width: 0%;
  transition: width 0.3s ease, background-color 0.3s ease;
}

.strength-0 {
  width: 20%;
  background-color: #ff5252;
}

.strength-1 {
  width: 40%;
  background-color: #ff9800;
}

.strength-2 {
  width: 60%;
  background-color: #ffc107;
}

.strength-3 {
  width: 80%;
  background-color: #4caf50;
}

.strength-4 {
  width: 100%;
  background-color: #2e7d32;
}

.password-strength-text {
  font-size: 12px;
  color: var(--text-light);
  margin-top: 4px;
  text-align: right;
}

/* 密码要求提示 */
.password-tips {
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.password-tips p {
  font-size: 14px;
  color: var(--text);
  margin-bottom: 8px;
  font-weight: 500;
}

.password-tips ul {
  list-style: none;
  padding-left: 0;
}

.password-tips li {
  font-size: 13px;
  color: var(--text-light);
  margin-bottom: 4px;
  position: relative;
  padding-left: 20px;
}

.password-tips li:before {
  content: "•";
  position: absolute;
  left: 0;
  color: var(--text-light);
}

.password-tips li.valid {
  color: var(--success);
}

.password-tips li.valid:before {
  color: var(--success);
  content: "✓";
}

/* 表单按钮 */
.el-form-item:last-child {
  margin-top: 30px;
  text-align: center;
}

.el-button {
  min-width: 120px;
  margin: 0 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .main-content {
    padding: 20px;
  }

  .password-form-card {
    padding: 20px;
  }

  .el-form-item:last-child {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .el-button {
    width: 100%;
    margin: 5px 0;
  }
}
</style>
